{% extends 'base.html' %}
{% load form_filters %}
{% load static %}

{% block content %}
<div class="container-fluid">
    <!-- 固定头部 -->
    <div class="fixed-top bg-white border-bottom" style="top: 0;">
        <div class="container-fluid py-3">
            <div class="row align-items-center">
                <div class="col">
                    <h2 class="mb-0">{{ form_template.title|default:'新建表单' }}</h2>
                </div>
                <div class="col-auto">
                    <button type="button" class="btn btn-primary me-2" onclick="saveForm()">保存表单</button>
                    <a href="{% url 'form_list' tenant.id %}" class="btn btn-outline-secondary">返回列表</a>
                </div>
            </div>
        </div>
    </div>

    <!-- 主要内容区域 -->
    <div class="row" style="margin-top: 80px;">
        <!-- 左侧：字段类型列表 -->
        <div class="col-md-3">
            <div class="position-sticky" style="top: 100px;">
                <div class="card">
                    <div class="card-header">
                        <h5 class="mb-0">可用组件</h5>
                    </div>
                    <div class="list-group list-group-flush field-types">
                        <!-- 添加字段组按钮 -->
                        <button class="list-group-item list-group-item-action list-group-item-primary" data-field-type="section">
                            <i class="bi bi-collection"></i> 添加字段组
                        </button>
                        <div class="list-group-item disabled">字段类型</div>
                        <button class="list-group-item list-group-item-action" data-field-type="text">
                            <i class="bi bi-input-cursor-text"></i> 文本框
                        </button>
                        <button class="list-group-item list-group-item-action" data-field-type="number">
                            <i class="bi bi-123"></i> 数字框
                        </button>
                        <button class="list-group-item list-group-item-action" data-field-type="radio">
                            <i class="bi bi-record-circle"></i> 单选框
                        </button>
                        <button class="list-group-item list-group-item-action" data-field-type="checkbox">
                            <i class="bi bi-check-square"></i> 复选框
                        </button>
                        <button class="list-group-item list-group-item-action" data-field-type="select">
                            <i class="bi bi-menu-down"></i> 下拉菜单
                        </button>
                        <button class="list-group-item list-group-item-action" data-field-type="image">
                            <i class="bi bi-image"></i> 图片上传
                        </button>
                    </div>
                </div>
            </div>
        </div>

        <!-- 右侧：表单设计区域 -->
        <div class="col-md-9">
            <!-- 表单基本信息 -->
            <div class="card mb-4">
                <div class="card-header">
                    <h5 class="mb-0">表单基本信息</h5>
                </div>
                <div class="card-body">
                    <div class="mb-3">
                        <label class="form-label">表单标题</label>
                        <input type="text" class="form-control" id="form-title" value="{{ form_template.title|default:'' }}" required>
                    </div>
                </div>
            </div>

            <!-- 字段列表 -->
            <div id="fields-container">
                <!-- 字段组将被动态添加到这里 -->
            </div>

            <!-- 字段模板 -->
            <template id="field-template">
                <div class="card mb-3 form-field" data-field-id="">
                    <div class="card-header d-flex justify-content-between align-items-center">
                        <h6 class="mb-0">新字段</h6>
                        <div class="btn-group">
                            <button type="button" class="btn btn-sm btn-outline-secondary move-up">
                                <i class="bi bi-arrow-up"></i>
                            </button>
                            <button type="button" class="btn btn-sm btn-outline-secondary move-down">
                                <i class="bi bi-arrow-down"></i>
                            </button>
                            <button type="button" class="btn btn-sm btn-outline-danger delete-field">
                                <i class="bi bi-trash"></i>
                            </button>
                        </div>
                    </div>
                    <div class="card-body">
                        <div class="row">
                            <div class="col-md-6">
                                <div class="mb-3">
                                    <label class="form-label">字段标签</label>
                                    <input type="text" class="form-control field-label" required>
                                </div>
                            </div>
                            <div class="col-md-6">
                                <div class="mb-3">
                                    <label class="form-label">字段类型</label>
                                    <input type="text" class="form-control field-type" readonly>
                                </div>
                            </div>
                        </div>
                        <div class="row">
                            <div class="col-md-12">
                                <div class="mb-3 options-container" style="display: none;">
                                    <label class="form-label">选项列表（用逗号分隔）</label>
                                    <input type="text" class="form-control field-options" placeholder="选项1,选项2,选项3">
                                </div>
                            </div>
                        </div>
                        <div class="form-check">
                            <input type="checkbox" class="form-check-input field-required" id="">
                            <label class="form-check-label">必填字段</label>
                        </div>
                    </div>
                </div>
            </template>

            <!-- 字段组模板 -->
            <template id="section-template">
                <div class="card mb-4 form-section" data-section-id="">
                    <div class="card-header bg-primary text-white d-flex justify-content-between align-items-center">
                        <div class="section-header-content">
                            <input type="text" class="section-title form-control-plaintext" 
                                   value="新建字段组" placeholder="请输入字段组名称">
                            <span class="badge field-count">0 个字段</span>
                        </div>
                        <div class="btn-group">
                            <button type="button" class="btn btn-sm btn-outline-light move-section-up">
                                <i class="bi bi-arrow-up"></i>
                            </button>
                            <button type="button" class="btn btn-sm btn-outline-light move-section-down">
                                <i class="bi bi-arrow-down"></i>
                            </button>
                            <button type="button" class="btn btn-sm btn-outline-light delete-section">
                                <i class="bi bi-trash"></i>
                            </button>
                        </div>
                    </div>
                    <div class="card-body section-fields">
                        <div class="text-center text-muted empty-section-tip">
                            <i class="bi bi-arrow-left-circle"></i> 
                            从左侧选择字段类型添加到此组
                        </div>
                    </div>
                </div>
            </template>
        </div>
    </div>
</div>

<!-- 添加 CSRF 令牌 -->
{% csrf_token %}

<!-- 添加样式和脚本 -->
<link href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.7.2/font/bootstrap-icons.css" rel="stylesheet">
<style>
    .field-types .list-group-item {
        cursor: pointer;
    }
    .field-types .list-group-item:hover {
        background-color: #f8f9fa;
    }
    .form-field {
        transition: all 0.3s ease;
    }
    .form-field:hover {
        box-shadow: 0 0 10px rgba(0,0,0,0.1);
    }
    .form-section {
        transition: all 0.3s ease;
        border: 2px solid transparent;
    }
    .form-section:hover {
        box-shadow: 0 0 15px rgba(0,0,0,0.1);
    }
    .active-section {
        border-color: #0d6efd;
    }
    .section-title {
        background: transparent;
        border: none;
        color: white !important;
        width: auto;
        min-width: 200px;
        padding: 0.375rem 0.75rem;
    }
    .section-title:focus {
        background: rgba(255, 255, 255, 0.1);
        color: white !important;
        outline: none;
        border-radius: 4px;
    }
    .section-title::placeholder {
        color: rgba(255, 255, 255, 0.8);
    }
    .section-header-content {
        display: flex;
        align-items: center;
        gap: 1rem;
    }
    .field-count {
        font-size: 0.8rem;
        background: rgba(255, 255, 255, 0.9) !important;
        color: #0d6efd !important;
        padding: 0.25rem 0.5rem;
        border-radius: 0.25rem;
    }
    .empty-section-tip {
        padding: 2rem;
        font-size: 1.1rem;
        color: #6c757d;
    }
    .field-count {
        font-size: 0.8rem;
    }
</style>

<script>
let sectionCounter = 0;
let fieldCounter = 0;
let activeSection = null;

// 初始化表单数据
function initializeForm() {
    {% if form_template %}
        console.log('Initializing form template:', {{ form_template.id }});
        
        // 设置表单标题
        document.getElementById('form-title').value = '{{ form_template.title|escapejs }}';
        
        // 创建字段组和字段
        {% for section in form_template.sections.all %}
            console.log('Creating section:', '{{ section.title|escapejs }}');
            
            // 创建字段组
            const sectionElement = addSection();
            if (!sectionElement) {
                console.error('Failed to create section element');
                continue;
            }
            
            // 设置字段组标题
            const titleInput = sectionElement.querySelector('.section-title');
            if (titleInput) {
                titleInput.value = '{{ section.title|escapejs }}';
            }
            
            // 创建字段
            {% for field in section.formfield_set.all %}
                console.log('Creating field:', '{{ field.label|escapejs }}');
                
                // 创建字段
                const fieldElement = addField('{{ field.field_type|escapejs }}', sectionElement);
                if (!fieldElement) {
                    console.error('Failed to create field element');
                    continue;
                }
                
                // 设置字段标签
                const labelInput = fieldElement.querySelector('.field-label');
                if (labelInput) {
                    labelInput.value = '{{ field.label|escapejs }}';
                }
                
                // 设置必填状态
                const requiredCheckbox = fieldElement.querySelector('.field-required');
                if (requiredCheckbox) {
                    requiredCheckbox.checked = {{ field.required|yesno:"true,false" }};
                }
                
                // 设置选项（如果有）
                {% if field.options %}
                    const optionsContainer = fieldElement.querySelector('.options-container');
                    if (optionsContainer) {
                        optionsContainer.style.display = 'block';
                        const optionsInput = optionsContainer.querySelector('.field-options');
                        if (optionsInput) {
                            optionsInput.value = '{{ field.options|escapejs }}';
                        }
                    }
                {% endif %}
            {% endfor %}
            
            // 更新字段计数
            updateFieldCount(sectionElement);
            
            // 隐藏空提示（如果有字段）
            if (sectionElement.querySelectorAll('.form-field').length > 0) {
                const emptyTip = sectionElement.querySelector('.empty-section-tip');
                if (emptyTip) {
                    emptyTip.style.display = 'none';
                }
            }
        {% endfor %}
    {% else %}
        // 新表单自动添加一个字段组
        addSection();
    {% endif %}
}

// 添加字段组
function addSection() {
    const template = document.getElementById('section-template');
    const container = document.getElementById('fields-container');
    const clone = template.content.cloneNode(true);
    
    sectionCounter++;
    const sectionElement = clone.querySelector('.form-section');
    sectionElement.dataset.sectionId = `section-${sectionCounter}`;
    
    // 绑定事件
    bindSectionEvents(sectionElement);
    
    container.appendChild(sectionElement);
    updateActiveSectionStatus(sectionElement);
    return sectionElement;
}

// 添加字段
function addField(fieldType, section) {
    const template = document.getElementById('field-template');
    const container = section.querySelector('.section-fields');
    const clone = template.content.cloneNode(true);
    
    fieldCounter++;
    const fieldElement = clone.querySelector('.form-field');
    fieldElement.dataset.fieldId = `field-${fieldCounter}`;
    
    // 设置字段类型
    fieldElement.querySelector('.field-type').value = fieldType;
    
    // 设置字段标题
    const fieldTypeText = document.querySelector(`[data-field-type="${fieldType}"]`).textContent.trim();
    fieldElement.querySelector('.card-header h6').textContent = fieldTypeText;
    
    // 显示选项输入框（如果需要）
    if (['radio', 'checkbox', 'select'].includes(fieldType)) {
        fieldElement.querySelector('.options-container').style.display = 'block';
    }
    
    // 绑定事件
    bindFieldEvents(fieldElement, section);
    
    container.appendChild(fieldElement);
    updateFieldCount(section);
    
    // 隐藏空提示
    section.querySelector('.empty-section-tip').style.display = 'none';
    
    return fieldElement;
}

// 绑定字段组事件
function bindSectionEvents(sectionElement) {
    // 删除字段组
    sectionElement.querySelector('.delete-section').addEventListener('click', function(e) {
        e.stopPropagation();
        if (confirm('确定要删除这个字段组及其所有字段吗？')) {
            if (sectionElement === activeSection) {
                activeSection = null;
            }
            sectionElement.remove();
        }
    });

    // 上移字段组
    sectionElement.querySelector('.move-section-up').addEventListener('click', function(e) {
        e.stopPropagation();
        const prev = sectionElement.previousElementSibling;
        if (prev) {
            sectionElement.parentNode.insertBefore(sectionElement, prev);
        }
    });

    // 下移字段组
    sectionElement.querySelector('.move-section-down').addEventListener('click', function(e) {
        e.stopPropagation();
        const next = sectionElement.nextElementSibling;
        if (next) {
            sectionElement.parentNode.insertBefore(next, sectionElement);
        }
    });

    // 点击字段组时设置为活动组
    sectionElement.addEventListener('click', function() {
        updateActiveSectionStatus(this);
    });
}

// 绑定字段事件
function bindFieldEvents(fieldElement, section) {
    // 删除字段
    fieldElement.querySelector('.delete-field').addEventListener('click', function(e) {
        e.stopPropagation();
        if (confirm('确定要删除这个字段吗？')) {
            fieldElement.remove();
            updateFieldCount(section);
            
            // 如果没有字段了，显示空提示
            if (section.querySelectorAll('.form-field').length === 0) {
                section.querySelector('.empty-section-tip').style.display = 'block';
            }
        }
    });

    // 上移字段
    fieldElement.querySelector('.move-up').addEventListener('click', function(e) {
        e.stopPropagation();
        const prev = fieldElement.previousElementSibling;
        if (prev && !prev.classList.contains('empty-section-tip')) {
            fieldElement.parentNode.insertBefore(fieldElement, prev);
        }
    });

    // 下移字段
    fieldElement.querySelector('.move-down').addEventListener('click', function(e) {
        e.stopPropagation();
        const next = fieldElement.nextElementSibling;
        if (next) {
            fieldElement.parentNode.insertBefore(next, fieldElement);
        }
    });

    // 设置必填字段的ID
    const fieldId = fieldElement.dataset.fieldId;
    const requiredCheckbox = fieldElement.querySelector('.field-required');
    requiredCheckbox.id = `required-${fieldId}`;
    fieldElement.querySelector('.form-check-label').setAttribute('for', `required-${fieldId}`);
}

// 修改 bindEventListeners 函数
function bindEventListeners() {
    // 字段组按钮
    const sectionButton = document.querySelector('[data-field-type="section"]');
    if (sectionButton) {
        // 移除可能存在的旧事件监听器
        const newButton = sectionButton.cloneNode(true);
        sectionButton.parentNode.replaceChild(newButton, sectionButton);
        newButton.addEventListener('click', addSection);
    }
    
    // 字段按钮
    document.querySelectorAll('.field-types button:not([data-field-type="section"])').forEach(button => {
        // 移除可能存在的旧事件监听器
        const newButton = button.cloneNode(true);
        button.parentNode.replaceChild(newButton, button);
        newButton.addEventListener('click', function() {
            if (!activeSection) {
                alert('请先创建或选择一个字段组');
                return;
            }
            addField(this.dataset.fieldType, activeSection);
        });
    });
}

// DOM 加载完成后初始化
document.addEventListener('DOMContentLoaded', function() {
    console.log('DOM loaded, initializing form...');
    
    // 首先绑定所有事件监听器
    bindEventListeners();
    console.log('Event listeners bound');
    
    // 然后初始化表单
    initializeForm();
    console.log('Form initialized');
});

// 更新字段计数
function updateFieldCount(section) {
    const count = section.querySelectorAll('.form-field').length;
    section.querySelector('.field-count').textContent = `${count} 个字段`;
}

// 更新活动字段组状态
function updateActiveSectionStatus(newActiveSection = null) {
    document.querySelectorAll('.form-section').forEach(section => {
        section.classList.remove('active-section');
    });
    
    activeSection = newActiveSection;
    if (activeSection) {
        activeSection.classList.add('active-section');
    }
}

// 添加字段类型点击事件
document.querySelectorAll('.field-types button').forEach(button => {
    button.addEventListener('click', function() {
        const fieldType = this.dataset.fieldType;
        if (fieldType === 'section') {
            addSection();
        } else if (activeSection) {
            addField(fieldType, activeSection);
        } else {
            alert('请先创建或选择一个字段组');
        }
    });
});

// 在现有的 JavaScript 代码中添加保存函数
function saveForm() {
    const formData = {
        {% if form_template %}id: {{ form_template.id }},{% endif %}
        title: document.getElementById('form-title').value,
        sections: []
    };
    
    if (!formData.title) {
        alert('请输入表单标题');
        return;
    }
    
    let hasError = false;
    let sectionOrder = 1;
    let fieldOrder = 1;
    
    document.querySelectorAll('.form-section').forEach((sectionElement) => {
        const section = {
            title: sectionElement.querySelector('.section-title').value || `第 ${sectionOrder} 组`,
            order: sectionOrder++,
            fields: []
        };
        
        sectionElement.querySelectorAll('.form-field').forEach(fieldElement => {
            const field = {
                label: fieldElement.querySelector('.field-label').value,
                field_type: fieldElement.querySelector('.field-type').value,
                required: fieldElement.querySelector('.field-required').checked,
                order: fieldOrder++,
                options: null
            };
            
            // 获取选项值
            if (['radio', 'checkbox', 'select'].includes(field.field_type)) {
                const optionsInput = fieldElement.querySelector('.field-options');
                if (optionsInput) {
                    field.options = optionsInput.value.trim();
                }
            }
            
            if (!field.label) {
                alert('请为所有字段填写标签');
                hasError = true;
                return;
            }
            
            if (['radio', 'checkbox', 'select'].includes(field.field_type) && !field.options) {
                alert(`请为 "${field.label}" 添加选项`);
                hasError = true;
                return;
            }
            
            section.fields.push(field);
        });
        
        if (section.fields.length === 0) {
            alert(`第 ${section.order} 组没有添加任何字段`);
            hasError = true;
            return;
        }
        
        formData.sections.push(section);
    });
    
    if (hasError) return;
    
    if (formData.sections.length === 0) {
        alert('请至少添加一个字段组');
        return;
    }
    
    // 发送到服务器
    fetch("{% url 'save_form_template' tenant.id %}", {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
            'X-CSRFToken': document.querySelector('[name=csrfmiddlewaretoken]').value
        },
        body: JSON.stringify(formData)
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            window.location.href = "{% url 'form_list' tenant.id %}";
        } else {
            alert(data.error || '保存失败');
        }
    })
    .catch(error => {
        console.error('Error:', error);
        alert('保存失败');
    });
}
</script>
{% endblock %} 